package com.osgix.common.mvc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * Dec 31, 2009,3:19:59 AM
 * @author azheng
 * 处理 Ajax 多方法调用
 * @version 2.0
 */
public abstract class AbsMultiActionController extends MultiActionController implements InitializingBean {

	/**
	 * 国际化处理
	 * @param i18nKey
	 * @return
	 */
	protected String i18n(String i18nKey) {
		return getApplicationContext().getMessage(i18nKey, null, null);
	}

	/**
	 * 取得所有请求参数放入Map中
	 * Dec 29, 2009,8:17:41 AM
	 * @author azheng
	 * @param request
	 * @return
	 */
	protected Map<String, String> getAllParams(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					//System.out.println("param: " + paramName + "=" + paramValue);
					map.put(paramName, paramValue);
				}
			}
		}
		return map;
	}

	/**
	 * 输出json
	 * Dec 31, 2009,6:03:43 AM
	 * @author azheng
	 * @param jsonStr
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	protected void outPutJson(String jsonStr, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		PrintWriter out = response.getWriter();
		out.print(jsonStr);
		out.close();
	}

}
